/**
 * Created by Adam on 2017/5/18.
 */
import React from 'react'
import { login, loginError } from '../actions'
import { connect } from 'react-redux'
import { browserHistory } from 'react-router'
import { TextField } from 'material-ui'
import { RaisedButton } from 'material-ui'
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import { Field, reduxForm } from 'redux-form'

class Login extends React.Component {
    componentWillMount() {
        const { isLoggedIn, redirectUrl } = this.props
        if (isLoggedIn) {
            browserHistory.push(redirectUrl)
        }
    }

    componentWillReceiveProps(nextProps) {
        const { isLoggedIn, redirectUrl } = nextProps
        const { isLoggedIn: wasLoggedIn } = this.props
        if (!wasLoggedIn && isLoggedIn) {
            browserHistory.push(redirectUrl)
        }
    }

    onSubmit = (values) => {
        const {dispatch} = this.props
        const { username, password } = values
        if (username === 'admin' && password === 'admin') {
            dispatch(login(username, password))
        } else {
            dispatch(loginError('username or password invalid'))
        }
    }

    render() {
        return (
            <ReduxLoginForm onSubmit={this.onSubmit}/>
        )
    }
}

export const renderTextField = ({input, label, meta: {touched, error}, ...custom}) => {
    return(
    <TextField
        hintText={label}
        floatingLabelText={label}
        errorText={touched && error}
        {...input}
        {...custom}
    />
)}

const LoginForm = ({ handleSubmit, pristine, reset, submitting }) => (
    <MuiThemeProvider>
        <form onSubmit={handleSubmit} style={{margin: '0 auto', width: 200, height: 400}}>
            <div>
                <Field name="username" type="text" label="Username" component={renderTextField}/>
            </div>
            <div>
                <Field name="password" type="password" label="Password" component={renderTextField}/>
            </div>
            <div>
                <RaisedButton label="Login" primary={true} type="submit" />
            </div>
        </form>
    </MuiThemeProvider>
)

let ReduxLoginForm = reduxForm({
    form: 'loginForm' // a unique identifier for this form
})(LoginForm)

const mapStateToProps = (state) => {
    return {
        errorMsg: state.loginInfo.errorMsg,
        redirectUrl: state.loginInfo.redirectUrl,
        isLoggedIn: state.loginInfo.isLoggedIn
    }
}

Login = connect(mapStateToProps)(Login)

export default Login